using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Product DAL/DTO object
	/// </summary>
	public static partial class ProductExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Product item, ProductDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Product DTO cannot be null.");
			if (item == null) throw new Exception("The Product item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			if (dtoItem.CategoryId == null) dr["CategoryID"] = System.DBNull.Value;
			else dr["CategoryID"] = dtoItem.CategoryId;
			if (dtoItem.UnitsOnOrder == null) dr["UnitsOnOrder"] = System.DBNull.Value;
			else dr["UnitsOnOrder"] = dtoItem.UnitsOnOrder;
			if (dtoItem.UnitsInStock == null) dr["UnitsInStock"] = System.DBNull.Value;
			else dr["UnitsInStock"] = dtoItem.UnitsInStock;
			if (dtoItem.UnitPrice == null) dr["UnitPrice"] = System.DBNull.Value;
			else dr["UnitPrice"] = dtoItem.UnitPrice;
			if (dtoItem.SupplierId == null) dr["SupplierID"] = System.DBNull.Value;
			else dr["SupplierID"] = dtoItem.SupplierId;
			if (dtoItem.ReorderLevel == null) dr["ReorderLevel"] = System.DBNull.Value;
			else dr["ReorderLevel"] = dtoItem.ReorderLevel;
			if (dtoItem.QuantityPerUnit == null) dr["QuantityPerUnit"] = System.DBNull.Value;
			else dr["QuantityPerUnit"] = dtoItem.QuantityPerUnit;
			dr["ProductName"] = dtoItem.ProductName;
			dr["ProductID"] = dtoItem.ProductId;
			dr["Discontinued"] = dtoItem.Discontinued;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="productCollection">The source DAL collection.</param>
		public static void Fill(this List<ProductDTO> list, ProductCollection productCollection)
		{
			if (productCollection == null) throw new Exception("The Product collection cannot be null.");
			if (list == null) list = new List<ProductDTO>();
			foreach (Product item in productCollection)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this ProductDTO dtoItem, Product item)
		{
			if (dtoItem == null) throw new Exception("The Product DTO cannot be null.");
			if (item == null) throw new Exception("The Product item cannot be null.");
			dtoItem.CategoryId = item.CategoryId;
			dtoItem.UnitsOnOrder = item.UnitsOnOrder;
			dtoItem.UnitsInStock = item.UnitsInStock;
			dtoItem.UnitPrice = item.UnitPrice;
			dtoItem.SupplierId = item.SupplierId;
			dtoItem.ReorderLevel = item.ReorderLevel;
			dtoItem.QuantityPerUnit = item.QuantityPerUnit;
			dtoItem.ProductName = item.ProductName;
			dtoItem.ProductId = item.ProductId;
			dtoItem.Discontinued = item.Discontinued;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<ProductDTO> list)
		{
			if (list == null) list = new List<ProductDTO>();
			ProductCollection retval = ProductCollection.RunSelect();
			foreach (Product item in retval)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<ProductDTO> list, Expression<Func<ProductQuery, bool>> where)
		{
			if (list == null) list = new List<ProductDTO>();
			list.Fill(ProductCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<ProductDTO> RunSelect(this List<ProductDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<ProductDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Product.FieldNameConstants sortField;
			try
			{
				sortField = (Product.FieldNameConstants)Enum.Parse(typeof(Product.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<ProductDTO> retVal = new PagedQueryResults<ProductDTO>();
			ProductPaging paging = new ProductPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new ProductPagingFieldItem(sortField, ascending));

			ProductCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = ProductCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Product");
				dalList = (ProductCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<ProductDTO>();
			foreach (Product item in dalList)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<ProductDTO> list, string linq)
		{
			if (list == null) list = new List<ProductDTO>();

			ProductCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = ProductCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Product");
				dalList = (ProductCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<ProductDTO>();
			foreach (Product item in dalList)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static ProductDTO Persist(this ProductDTO product)
		{
			if (product == null) throw new Exception("The Product DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Product newItem = null;
			ProductCollection newCollection = null;

			bool isIdentityChecked = false;
			isIdentityChecked = true;
			if(isIdentityChecked)
			{
				if (product.ProductId > 0)
				{
					newItem = ACME.Northwind.Business.Objects.Product.SelectUsingPK(product.ProductId);
					newCollection = newItem.ParentCollection;
				}
				else
				{
					if (product.ProductId == 0) product.ProductId = -1;
					newCollection = new ProductCollection();
					newItem = newCollection.NewItem();
				}
			}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Product.SelectUsingPK(product.ProductId);
				if (newItem == null)
				{
					newCollection = new ProductCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(product);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			product.Fill(newItem);
			return product;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<ProductDTO> productList)
		{
			if (productList == null) throw new Exception("The Product DTO list cannot be null.");
			//Get all objects from the database that match PK
			ProductCollection productCollection = new ProductCollection();
			List<ProductPrimaryKey> keyList = new List<ProductPrimaryKey>();
			foreach (ProductDTO dto in productList)
			{
				keyList.Add(new ProductPrimaryKey(dto.ProductId));
			}			
			productCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.ProductSelectByPks(keyList));
			productCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (ProductDTO dto in productList)
			{
				Product product = (from x in (IEnumerable<Product>)productCollection
					where x.ProductId == dto.ProductId
					select x).FirstOrDefault();

				if (product == null) product = productCollection.NewItem();
				product.Fill(dto);
				if (!product.IsParented) productCollection.AddItem(product);
			}
			productCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<ProductDTO> deletedList = new List<ProductDTO>();
			foreach (ProductDTO dto in productList)
			{
				Product product = (from x in (IEnumerable<Product>)productCollection
					where x.ProductId == dto.ProductId
					select x).FirstOrDefault();

				if (product != null) dto.Fill(product);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (ProductDTO dto in deletedList)
			{
				productList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Product Select by Column

		#endregion

		#region Product SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this ProductDTO product, int productid)
		{
			Product item = ACME.Northwind.Business.Objects.Product.SelectUsingPK(productid);
			if (item == null) return false;
			product.Fill(item);
			return true;
		}

		#endregion

		#region Product Select By Foreign Key

		/// <summary>
		/// Populate a 'Category' DTO object collection from its relationship with the 'Product' table.
		/// </summary>
		public static void SelectByCategory(this List<ProductDTO> ProductList, int categoryid)
		{
			ProductCollection list = ProductCollection.RunSelect(x => x.CategoryId == categoryid);
			foreach (Product item in list)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				ProductList.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a 'Supplier' DTO object collection from its relationship with the 'Product' table.
		/// </summary>
		public static void SelectBySupplier(this List<ProductDTO> ProductList, int supplierid)
		{
			ProductCollection list = ProductCollection.RunSelect(x => x.SupplierId == supplierid);
			foreach (Product item in list)
			{
				ProductDTO newItem = new ProductDTO();
				newItem.Fill(item);
				ProductList.Add(newItem);
			}
		}

		#endregion

		#region Product Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this ProductDTO product)
		{
			Product item = ACME.Northwind.Business.Objects.Product.SelectUsingPK(product.ProductId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
